import React, { useEffect, useState, useRef, forwardRef } from 'react';
import TitleLine from 'components/common/titleLine';
import CheckPanel from 'components/common/checkPanel';
import router from 'umi/router';
import { connect } from 'dva';
import { Button, message } from 'antd';
import UploadPanel from 'components/common/uploadPanel';
import UploadPanelIE from 'components/common/uploadPanelIE';
import { IsIE_nine } from 'utils/format'
import DeviceMessage from 'components/common/deviceMessage';
import MaintenanceMessage from 'components/common/maintenanceMessage';
import PlanBasicMessage from '../components/planBasicMessage';
import HasFinish from '../components/hasFinish'
import KeepAlive from 'react-activation'

import './index.styl';
let UploadPanelRef;
if (IsIE_nine() === 9) {
  UploadPanelRef = forwardRef((props, ref) => (
    <UploadPanelIE {...props} cRef={ref} />
  ));
} else {
  UploadPanelRef = forwardRef((props, ref) => (
    <UploadPanel {...props} cRef={ref} />
  ));
}

function Detail({ dispatch, location, deviceCali: { details, progressList }, commonAction: { catchObj } }) {
  const { id } = location.query;
  const { userId } = JSON.parse(sessionStorage.getItem('loginInfo'));
  const [list, setList] = useState([]);
  const [flag, setFlag] = useState(0)
  const [uploadFileList, setUploadFileList] = useState([])
  const uploadPanelRef = useRef()
  useEffect(() => {
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          deviceCali_detail: [true, false]
        }
      }
    })
  },[dispatch])
  useEffect(() => {
    dispatch({
      type: 'deviceCali/getDetails',
      payload: { id },
    })
  }, [dispatch, id]);

  useEffect(() => {
    if (details && JSON.stringify(details) !== '{}') {
      setUploadFileList(details.assayFileSet)
    }
  },[details])
  // 获取节点流程
  useEffect(() => {
    if (details && details.procInsId) {
      dispatch({
        type: 'deviceCali/getProgress',
        payload: { id: details && details.procInsId },
      });
    }
  }, [details, dispatch]);
  // 更新节点流程
  const getListAgain = () => {
    dispatch({
      type: 'deviceCali/getProgress',
      payload: { id: details && details.procInsId },
    });
  }
  function finishItem() {
    // const nowTime = Date.parse(new Date());
    // console.log(nowTime)
    // const endTime = new Date(Date.parse(detail.endTime.replace(/-/g, '/') + '23:59:59'));
    // const endTime = Date.parse(detail.endTime + ' 23:59:59');
    console.log(uploadPanelRef.current.fileName.every(item => item.show === true))
    if (!(uploadPanelRef.current.fileName.every(item => item.show === true))) {
      message.info('文件上传中，请稍后提交')
      return
    }
    if (uploadPanelRef.current.fileLists.length === 0) {
      message.error('请先上传文件');
      return;
    }
    const arry = [];
    uploadPanelRef.current.fileLists.map(i => {
      arry.push({
        fileName: i.name || i.fileName,
        fileType: i.typeCode || i.fileType,
        fileUrl: (i.response && i.response.data && i.response.data.url) || i.fileUrl,
      });
    });
    dispatch({
      type: 'deviceCali/finishPlanFn',
      payload: {
        id,
        assayFileForms: [...arry],
      },
    });
  }
  return (
    <KeepAlive name="deviceCali_detail" when={catchObj.deviceCali_detail}>
      <div className="deviceCali_detail" id="deviceCali_detail">
        <div className="detail_1">
          <PlanBasicMessage basicInfo={details} />
          <div className="deviceInfo">
            <div style={{ width: '6.2rem' }}>
              <DeviceMessage title="设备信息" deviceInfo={details && details.deviceVo} isDetail={true}/>
            </div>
            <div>
              <MaintenanceMessage title="检定员信息" maintenanceInfo={details && details.userVo} />
            </div>
          </div>
          <TitleLine title={'检定报告'} />
          <UploadPanelRef
            ref={uploadPanelRef}
            index={0}
            editFileList={(details && details.assayFileSet) || []}
            isNone={details && details.actionStatus === 2 && details.assayUser === userId && details.status !== 4}
            getFileList={v => setList(v)}
            num={10}
            mb={100}
            uploadNum={(val) => setFlag(val)}
            flag={flag}
            id={id}
            tip='检定报告'
          />
          <div className="deviceCali_detail-hasFinish">
            {
              details && details.actionStatus === 4 && details.assayFileSet.length > 0 && details.assayFileSet.map(item => {
                return <HasFinish key={item.id} item={item} />
              })
            }
          </div>
          {details && details.assayUser === userId && details.actionStatus === 2 && details.status !== 4 ? ( // 当前登录用户是当前检定员
            <div style={{ textAlign: 'center' }}>
              <Button className="blue-button" onClick={finishItem}>
                完成计划
            </Button>
            </div>
          ) : null}
        </div>
        <div className="detail_2">
          <CheckPanel
            id={id}
            processType={'assay'}
            list={progressList && progressList.slice(1, progressList.length)}
            getListAgain={getListAgain}
            linkTo={() => {
              router.push({
                pathname: '/deviceCali',
                params: { isRefresh: true }
              })
            }}
          />
        </div>
      </div>
    </KeepAlive>
  );
}

export default connect(({ deviceCali, commonAction }) => ({
  deviceCali, commonAction
}))(Detail);
